<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-05-28
 * Time: 11:58
 * 县区管理类
 */

namespace app\api\controller\v1;

use app\api\model\County as CountyModel;
use app\api\model\CountyPartner;
use app\api\model\Province;
use think\facade\Request;

class County
{
    /**
     * 获取全部
     */
    public function getDataAll($province_id,$city_id)
    {
        $where = [];
        if($province_id > 0) {
            $where[] = ['province_id','eq',$province_id];
        }
        if($city_id > 0) {
            $where[] = ['city_id','eq',$city_id];
        }
        return CountyModel::where($where)->order('update_time desc')
            ->select()->toArray();
    }
    /**
     * 获取列表
     * @validate('PagingParameter')
     * @auth('开放区/县','开放区域管理')
     */
    public function getDataList($page,$limit,$name,$province_id,$city_id)
    {
        $where = [];
        if($name) {
            $where[] = ['name','like','%'.$name.'%'];
        }
        if($province_id > 0) {
            $where[] = ['province_id','eq',$province_id];
        }
        if($city_id > 0) {
            $where[] = ['city_id','eq',$city_id];
        }
        $query = CountyModel::with('province,city')->where($where)->order('update_time desc');
        $count = $query->count();
        $result = $query->page($page, $limit)->select();
        $data['count'] = $count;
        $data['data'] = $result;
        return $data;
    }

    /**
     * 获取详情
     * @validate('IdMustBePositiveInt')
     */
    public function getDataInfo($id)
    {
        return CountyModel::where('id',$id)->find();
    }

    /**
     * 创建分类
     * @validate('CheckCounty')
     */
    public function createData()
    {
        $data = Request::post();
        $mode = CountyModel::create($data);
        $province = Province::get($data['province_id']);
        $city = Province::get($data['city_id']);
        $info = CountyPartner::where('province',$province['name'])
            ->where('city',$city['name'])
            ->where('county',$data['name'])
            ->find();
        if($info) {
            CountyPartner::where('id',$info['id'])->update([
                'county_id' => $mode->id
            ]);
        }
        return writeJson(201, [], '添加成功！');
    }

    /**
     * 更新信息
     * @validate('CheckCounty')
     */
    public function updateData()
    {
        $data = Request::put();
        $mode = new CountyModel();
        $mode->allowField(true)->save($data,['id',$data['id']]);
        return writeJson(202, [], '修改成功！');
    }

    /**
     * 删除信息
     * @validate('IdMustBePositiveInt')
     */
    public function deleteData($id)
    {
        CountyModel::destroy($id);
        return writeJson(203, [], '删除成功！');
    }
}